package com.hongji.lms5xxcommunicator.grid.update;

import com.hongji.lms5xxcommunicator.grid.core.RasterState;

import java.util.HashMap;
import java.util.Map;

/**
 * 严格替换式更新策略：同一批次内落入同一格的点，保留“最后一个”的值；
 * 写回时直接覆盖该格（sum=val, count=1, mean=val, hasData=true）。
 *
 * 作用：再次扫描同一格，地形立即改形，不存在“慢慢塌陷/长高”的拖尾。
 */
public class ReplaceUpdateStrategy implements UpdateStrategy {

    @Override
    public void apply(RasterState s, double[] xs, double[] ys, double[] zs) {
        if (s == null || xs == null || ys == null || zs == null) return;
        final int n = xs.length;
        if (ys.length != n || zs.length != n) return;

        final int cols = s.spec.cols;

        // 批内聚合：以 (r,c) 为 key，仅保留“最后一次”的 z
        final Map<Integer, Double> lastVal = new HashMap<>(Math.min(n, 1 << 16));

        for (int i = 0; i < n; i++) {
            final double x = xs[i], y = ys[i], z = zs[i];
            if (Double.isNaN(x) || Double.isNaN(y) || Double.isNaN(z)) continue;
            if (Double.isInfinite(x) || Double.isInfinite(y) || Double.isInfinite(z)) continue;

            final int r = s.spec.toRow(y);
            final int c = s.spec.toCol(x);
            if (!s.inBounds(r, c)) continue;

            final int key = r * cols + c;
            lastVal.put(key, z); // 后来的覆盖先前的
        }

        // 写回：严格替换
        for (Map.Entry<Integer, Double> e : lastVal.entrySet()) {
            final int key = e.getKey();
            final int r = key / cols;
            final int c = key % cols;
            final double v = e.getValue();

            s.sumZ[r][c]  = v;
            s.count[r][c] = 1;
            s.meanZ[r][c] = v;
            s.hasData[r][c] = true;
        }
    }
}
